import { Component, Vue, Prop, PropSync, Watch } from 'vue-property-decorator'
import styles from './ApplyInvoiceDialog.less'
import { Action } from 'vuex-class'

Component.registerHooks(['beforeRouteLeave'])

const statusList = {
  pending: 'pending',
  success: 'success',
}

@Component({})
export default class ApplyInvoiceDialog extends Vue {
  @Prop() payOrderId!: number
  @PropSync('dialogVisible', { default: false }) private visible!: boolean
  @Action('paymentOrder/invoiceDownLoad') private invoiceDownLoad!: any
  @Action('paymentOrder/queryInvoiceProduceStatus')
  private queryInvoiceProduceStatus!: any
  private status: string = statusList.pending
  private pollTimer: any
  private pollStarted: boolean = false // 轮询开始标志
  private timeout!: number

  handleClose() {
    this.visible = false
  }

  private render() {
    return (
      <el-dialog
        class={styles.applyInvoiceDialog}
        visible={this.visible}
        show-close={false}
        title={'提示'}
      >
        {this.status === statusList.pending && (
          <div>
            <p class={'main-content'}>
              <span>发票生成中，请耐心等待</span>
              <i class={'el-icon-loading'} />
            </p>
          </div>
        )}
        {this.status === statusList.success && (
          <div>
            <p class={'main-content'}>
              <span>申请开票成功</span>
              <i class={'el-icon-check'} style={'color: green'} />
            </p>
            <p class={'append-content'}>申请开票成功，是否下载发票？</p>
            <p class={'append-content'}>
              （温馨提示：2020年07月04日后的申请单，若已支付快递费，费用将一并包含在发票中。）
            </p>
          </div>
        )}
        <div slot={'footer'}>
          <el-button onClick={this.handleClose}>关闭</el-button>
          {this.status === statusList.success && (
            <el-button type={'primary'} onClick={this.download}>
              下载发票
            </el-button>
          )}
        </div>
      </el-dialog>
    )
  }

  @Watch('visible')
  onVisibleChange(visible: boolean) {
    if (visible) {
      this.pollStatus()
    } else {
      this.resetDialog()
    }
  }

  resetDialog() {
    this.status = statusList.pending
    this.pollStarted = false
    this.pollTimer && clearTimeout(this.pollTimer)
    this.timeout && clearTimeout(this.timeout)
    this.pollTimer = undefined
  }

  beforeRouteLeave(to: any, from: any, next: any) {
    this.resetDialog()
    next()
  }

  async pollStatus() {
    if (!this.pollStarted) {
      // 轮询超时5分钟
      this.timeout = setTimeout(() => {
        this.errorHandler()
      }, 5 * 60 * 1000)
      this.pollStarted = true
    }

    const status = await this.queryStatus()
    // 开票中
    if (status === 3) {
      this.pollTimer = setTimeout(() => {
        this.pollStatus()
      }, 3000)
    }
    // 发票生成成功
    else if (status === 4) {
      this.status = statusList.success
      clearTimeout(this.timeout)
      this.$emit('success')
    }
    // 发票生成失败
    else if (status === 5) {
      clearTimeout(this.timeout)
      this.errorHandler()
    }
  }

  errorHandler() {
    this.visible = false
    this.$message.warning(
      '发票生成失败，请稍后再试。若需人工服务，请拨打4000878198转3(政务服务专线)'
    )
  }

  async queryStatus() {
    return this.queryInvoiceProduceStatus(this.payOrderId)
      .then((res: any) => {
        return res.data.invoiceStatus
      })
      .catch(() => {
        this.handleClose()
      })
  }

  download() {
    this.invoiceDownLoad(this.payOrderId)
  }
}
